<template>
  <div style="position: relative; height: 100%">
    <div class="todo-list-main">
      <StatisticTabsHeader v-show="isShowStatisticalToolBar"
                           :value="statisticTabsValue"
                           :tabsList="statisticTabsArray"
                           @handleChange="onStatisticTabsValueChange" />
      <div :id="searchConditionContainerId"></div>
      <div class="todo-list-header">
        <CommonCounter v-if="selectedRowKeys.length"
                       :total="total"
                       :currentSelected="selectedRowKeys.length"
                       @cancelSelected="cancelSelected" />
        <div style="flex: 1; overflow: hidden">
          <CommonToolbar :allToolBtns="allToolBtns"
                         @buttonClick="buttonClick"
                         @checkOnchange="checkOnchange">
          </CommonToolbar>
        </div>
        <div class="search-part">
          <div style="display: inline-block; width: 272px">
            <a-input-search :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                            style="width: 272px"
                            :allowClear="true"
                            v-model="searchValue"
                            @change="onInputSearchValueChange"
                            @search="onSearch" />
          </div>
          <div style="margin-left: 12px; display: flex">
            <SearchCondition :containerParentId="searchConditionContainerId"
                             :conditions="searchConditions"
                             @valueChange="onSearchConditionsValueChange"
                             @expandChange="onExpandChange"></SearchCondition>
          </div>
        </div>
      </div>
      <div class="todo-list-content">
        <div>
          <AVirtuallyTable ref="avirtuallyTable"
                           :row-selection="{
            columnWidth: 60,
            ...rowSelection
          }"
                           :rowKey="rowKey"
                           :pagination="true"
                           :paginationOption="pagination"
                           :columns="columns"
                           :openVirtuallyModel="true"
                           :dataSource="dataSource"
                           :rightClickMenus="rightClickMenus"
                           :titleRightMenus="titleRightMenus"
                           size="small"
                           :loading="loading"
                           :localstorageKey="getLocalStorageKey"
                           @paginationChange="handleTableChange"
                           @paginationShowSizeChange="paginationShowSizeChange"
                           @rowClick="onTableRowClick">
            <span slot="subject"
                  slot-scope="{ record }">
              <SubjectColumnRender :record="record"></SubjectColumnRender>
            </span>
            <span slot="nodeDeadLineName"
                  slot-scope="{ record }">
              <span v-if="record.isCoverTime"
                    class="color_red">{{ record.nodeDeadLineName }}</span>
              <span v-else>{{ record.nodeDeadLineName }}</span>
            </span>
            <span slot="subState"
                  slot-scope="{ record }">
              <SubStateColumnRender :record="record"></SubStateColumnRender>
            </span>
            <span slot="processId"
                  slot-scope="{ record }">
              <a class="icon-default ico16 view_log_16 noClick"
                 href="javascript:void(0)"
                 @click.stop="showDetailLogDialog(record)"></a>
            </span>
            <span slot="nodeName"
                  slot-scope="{ record }"
                  :title="formatAffairNodeName(record)">
              {{formatAffairNodeName(record)}}
            </span>
          </AVirtuallyTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import StatisticTabsHeader from '@/components/statistic-tabs-header/index';
  import CommonToolbar from '../../components/common-toolbar/index';
  import CommonCounter from '../../components/common-counter/index';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import SubjectColumnRender from './components/subject-column-render.vue';
  import SubStateColumnRender from './components/subState-column-render.vue';
  import {getParams, loadComponentsThemeDefaultCSS, toastForward} from '../../utils';
  import collaboration from '../../utils/collaboration.js';
  import smartCodeMixin from '../../mixins/smart-code-mixin';
  import { formatRequestDataToJSON } from '@/utils/api';
  import * as Fiber from 'fiber';
  export default {
    name: 'PendingList',
    mixins: [smartCodeMixin],
    components: {
      StatisticTabsHeader,
      CommonToolbar,
      CommonCounter,
      SearchCondition,
      AVirtuallyTable,
      SubjectColumnRender,
      SubStateColumnRender
    },
    data() {
      return {
        aiSortValueTemp: false,
        isShowStatisticalToolBar: true, // 是否显示顶部的统计控件
        statisticTabsValue: '', // 顶部统计控件选中值
        statisticTabsArray: [], // 顶部统计控件页签数组
        isShowTotal: true, // 是否显示统计控件的总数
        canDel: true,
        showBatchDeal: true, // //默认显示批处理
        searchConditionContainerId: 'search-condition-container-parent',
        searchConditions: [],
        urlParamObj: {},
        allToolBtns: [],
        total: 0,
        dataSource: [],
        columns: [],
        selectedRowKeys: [],
        rightClickMenus: null,
        titleRightMenus: {
          asc: true,
          desc: true,
          freeze: true,
          fieldset: true
        },
        pagination: {
          page: 1,
          total: 0
        },
        searchValue: '',
        selectedRows: [],
        rowKey: 'affairId',
        lockProcessIds: [],
        searchConditionsObj: {},
        loading: false
      };
    },
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
          // onSelect: this.onSelectRecord
        };
      },
      getLocalStorageKey() {
        return this.userId + this.pageKey;
      }
    },
    created() {
      this.initPageParam();
      if (window.globalMetadata !== null) {
        this.initMetadata(window.globalMetadata);
      } else {
        window.addCustomObserver('getMetadata', (data) => {
          this.initMetadata(data);
        });
      }
      if (window.globalTableData !== null) {
        this.initFirstScreenTableData(window.globalTableData);
      } else {
        window.addCustomObserver('getTableData', (data) => {
          this.initFirstScreenTableData(data);
        });
      }
      // this.getMetadata();
      // this.initTableData();
      window.addEventListener('storage', this.storageChangeEvent);
      window.closeAndFresh = this.initTableData;
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    mounted() {},
    beforeDestroy() {
      window.removeEventListener('storage', this.storageChangeEvent);
      delete window.closeAndFresh;
    },
    methods: {
      initPageParam() {
        this.process = null; // 全局loading对象
        this.pageKey = 'LIST_PENDING'; // 页面唯一标识
        this.userId = window._currentUser.id;
        this.urlParamObj = getParams(window.location.search);

        // 初始化v3x，工作流中会使用到
        // window.v3x = new V3X();
        // v3x.init(window._ctxPath, window._locale);
      },
      initMetadata(data) {
        if (data && data.globalParam) {
          this.formatGlobalParam(data.globalParam);
          this.initStatisticalToolBar(data.pageHead.items);
          this.searchConditions = data.searchConditions.filter((item) => {
            if (item.key == 'subject') {
              return false;
            } else {
              return true;
            }
          });
          this.columns = this.formatTableColumns(data.tableColumns);
          // this.initTableData();
          this.initToolbar();
          if (this.firstScreenCacheTableData) {
            this.initFirstScreenTableData(this.firstScreenCacheTableData);
          }
        }
      },
      initFirstScreenTableData(result) {
        if (this.columns.length <= 0) {
          // 如果列没有数据，说明元数据接口没返回，先不渲染表格
          this.firstScreenCacheTableData = result;
          return;
        } else {
          this.firstScreenCacheTableData = null;
        }
        if (result && result.data) {
          this.dataSource = result.data;
          this.total = result.total;
          this.pagination.total = result.total;
          this.updateTabsNumber();
        }
      },
      getMetadata() {
        const data = {
          key: this.pageKey, // 页面唯一标识（取值参照ListKey）
          platform: 0, // 终端 0 pc 1 mobile （取值参照PlatformType）
          arguments: {
            // 业务传参，由业务决定（后续可在元数据拦截器中获取到）
            userId: this.userId,
            bpmMenu: '',
            isSupervision: '',
            supervisionApproval: '',
            templateIds: this.urlParamObj.textfield || ''
          }
        };
        const url = `${window._ctxPath}/rest/global/metadata/list`;
        window.axios.post(url, data).then((res) => {
          if (res.data && res.data.code == 0) {
            const data = res.data.data;
            this.formatGlobalParam(data.globalParam);
            this.initStatisticalToolBar(data.pageHead.items);
            this.searchConditions = data.searchConditions.filter((item) => {
              if (item.key == 'subject') {
                return false;
              } else {
                return true;
              }
            });
            this.columns = this.formatTableColumns(data.tableColumns);
            // this.initTableData();
            this.initToolbar();
          }
        });
      },
      formatGlobalParam(globalParam) {
        const {
          aiSortValue,
          bpmMenu,
          canDel,
          isShowStatisticalToolBar,
          isShowTotal,
          paramTemplateIds,
          showBatchDeal,
          v5Member,
          supportSmartCode
        } = globalParam;
        this.aiSortValueTemp = aiSortValue ? aiSortValue : false;
        this.canDel = canDel;
        this.isShowStatisticalToolBar = isShowStatisticalToolBar === '1' ? true : false;
        this.isShowTotal = isShowTotal == '1' ? true : false;
        this.showBatchDeal = showBatchDeal;
        this.supportSmartCode = supportSmartCode;
      },
      formatTableColumns(tableColumns) {
        const customRenderColumns = [
          'subject',
          'nodeDeadLineName',
          'subState',
          'processId',
          'nodeName'
        ];
        const columns = tableColumns.filter((item) => {
          delete item.extra;
          item.dataIndex = item.key;
          item.dropdownMenus = {
            fieldset: true,
            desc: true,
            asc: true
          };
          if (customRenderColumns.includes(item.key)) {
            item.scopedSlots = { customRender: item.key };
          }
          item.customCell = (column) => {
            const fontBlod = this.isBlod(column) ? 'bold' : '';
            return {
              style: {
                'font-weight': fontBlod,
                cursor: 'pointer',
                padding: '0 8px'
              }
            };
          };
          if (item.key === this.rowKey) {
            return false;
          } else {
            return true;
          }
        });

        return columns;
      },
      isBlod(record) {
        const { readState, subState } = record;
        // 未读，加粗显示， 代理也要加粗
        if (readState === 0 || subState === 11) {
          return true;
        } else {
          return false;
        }
      },
      initStatisticalToolBar(items) {
        if (this.isShowStatisticalToolBar) {
          this.statisticTabsArray = items.map((item) => {
            if (this.isShowTotal) {
              item.hideValue = false;
            } else {
              item.hideValue = true;
            }

            return item;
          });
          this.statisticTabsValue = this.statisticTabsArray[0].key;
        }
      },
      initToolbar() {
        //转发协同和转发邮件需要由插件控制，先假设都有插件, morePending.jsp里面
        const hasNewColl = window._hasResource('F01_newColl');
        const hasMailCreate = window._hasResource('F12_mailcreate');

        // 转发
        if (hasNewColl || hasMailCreate) {
          const submenu = [];
          if (hasNewColl) {
            submenu.push({
              //转发协同
              id: 'transmitCol',
              name: this.$i18n('common.toolbar.transmit.col.label')
              // submenu.push({name: "${ctp:i18n('common.toolbar.transmit.col.label')}",click: transmitCol });
            });
          }
          if (hasMailCreate) {
            submenu.push({
              //转发邮件
              id: 'transmitMail',
              name: this.$i18n('common.toolbar.transmit.mail.label')
              // submenu.push({name: "${ctp:i18n('common.toolbar.transmit.mail.label')}",click: _transmitMail });
            });
          }
          this.allToolBtns.push({
            id: 'transmit',
            name: this.$i18n('common.toolbar.transmit.label'),
            // name: this.i18n('common.toolbar.transmit.label'),
            subMenu: submenu
          });
        }

        //归档
        if (this.isPigeonholeBtn() && window._hasPlugin('doc')) {
          this.allToolBtns.push({
            id: 'pigeonhole',
            name: this.$i18n('common.toolbar.pigeonhole.label')
          });
        }

        // 删除
        if (this.canDel) {
          this.allToolBtns.push({
            id: 'delete',
            name: this.$i18n('common.toolbar.delete.label')
          });
        }

        // 批处理
        if (this.showBatchDeal) {
          this.allToolBtns.push({
            id: 'batchDeal',
            name: this.$i18n('common.batch.handle.label')
          });
        }

        // 自动处理
        this.allToolBtns.push({
          id: 'autoDeal',
          name: this.$i18n('batch.autorun.label')
          // name: this.i18n('batch.autorun.label')
        });

        // 智能排序
        if (window._hasPlugin('ai')) {
          let checkValue = false;
          if (this.aiSortValueTemp) {
            checkValue = true;
          }
          this.allToolBtns.push({
            id: 'aiSortBtn',
            name: this.$i18n('ai.sort.labe'),
            type: 'checkbox',
            checked: checkValue,
            value: '1'
          });
        }

        // 扫一扫
        if (this.isHaveSmartCodePermission()) {
          // 有智码插件，并且不是vjoin平台
          this.allToolBtns.push(this.smartCodeBtnInfo);
        }
      },
      isPigeonholeBtn() {
        var hasResourceCode =
          window._hasResource('F04_docIndex') ||
          window._hasResource('F04_myDocLibIndex') ||
          window._hasResource('F04_accDocLibIndex') ||
          window._hasResource('F04_proDocLibIndex') ||
          window._hasResource('F04_eDocLibIndex') ||
          window._hasResource('F04_docLibsConfig');
        return hasResourceCode;
      },
      // initTableHeader() {},
      initTableData() {
        this.loading = true;
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
        const searchConditions = this.getSearchValueObj();
        const sendParams = [
          { page: this.pagination.page, size: this.pagination.pageSize },
          searchConditions
        ];
        const args = `managerMethod=getPendingList&arguments=${formatRequestDataToJSON(sendParams)}`;
        const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=colManager&rnd=33539`;

        if (this.cancelToken && this.cancelToken.cancel) {
          this.cancelToken.cancel();
          this.cancelToken = null;
        }
        this.cancelToken = axios.CancelToken.source();

        window.axios
          .post(url, args, {
            cancelToken: this.cancelToken.token,
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
          })
          .then((data, err) => {
            const result = data.data;
            if (result) {
              // 如果当前查询的页为非第一页，并且没有数据时，需要重新请求第一页的数据
              if (result.data.length === 0 && this.pagination.page !== 1) {
                this.pagination.page = 1;
                this.initTableData();
                return;
              }
              this.dataSource = result.data;
              this.total = result.total;
              this.pagination.total = result.total;
              this.pagination.page = result.page;
              this.updateTabsNumber();
            }

            this.loading = false;
          })
          .catch((error) => {
            console.error(error);
            this.loading = false;
          });
      },
      updateTabsNumber() {
        for (const item of this.statisticTabsArray) {
          if (item.key == this.statisticTabsValue) {
            item.value = this.total + '';
            break;
          }
        }
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRows = selectedRows;
      },
      // onSelectRecord(record, selected, selectedRows) {
      //   this.selectedRows = selectedRows;
      // },
      onInputSearchValueChange(e) {
        this.searchValue = e.target.value;
      },
      onSearch(e) {
        this.searchValue = e;
        this.pagination.page = 1;
        this.initTableData();
      },
      onStatisticTabsValueChange(value) {
        this.statisticTabsValue = value;
        this.initTableData();
      },
      // 筛选条件值改变
      onSearchConditionsValueChange(data) {
        this.searchConditionsObj = data;
        this.initTableData();
      },
      onExpandChange(isExpanded) {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.resizeTable();
        });
      },
      // searchCondition() {
      //   console.log('searchCondition');
      //   //TODO: 展开搜索条件
      // },

      // 取消表格中的勾选
      cancelSelected() {
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
      },
      //按钮点击事件
      buttonClick(buttonKey) {
        console.log('buttonKey', buttonKey);
        switch (buttonKey) {
          case 'transmitCol': // 转发协同
            this.transmitCol();
            break;
          case 'transmitMail': // 转发邮件
            this.transmitMail();
            break;
          case 'pigeonhole': // 归档
            collaboration.doPigeonhole(this.selectedRows, this.doPigeonholeCallback);
            break;
          case 'delete': // 删除
            this.deleteCol();
            break;
          case 'batchDeal': // 批处理
            this.batchHandler(this.selectedRows, this.initTableData);
            break;
          case 'autoDeal': // 自动处理
            window.batchAutoRun(this.batchAutoRunCallback);
            break;
          case 'smartCodeScan': // 扫一扫
            this.showSmartCode && this.showSmartCode();
        }
      },
      checkOnchange(data) {
        switch (data.id) {
          case 'aiSortBtn':
            this.aiSortValueTemp = data.checked;
            this.aiSortClick();
            break;
        }
      },
      transmitCol() {
        this.transmitColFromGrid();
      },
      doPigeonholeCallback(data) {
        if (data && data.success) {
          // TODO:归档成功刷新列表
          this.initTableData();
        }
      },

      //转发协同
      transmitColFromGrid(listFrom) {
        const rows = this.selectedRows;
        if (rows.length === 0) {
          //请选择要转发的协同
          Fiber.message.warning(this.$i18n('collaboration.grid.alert.transmitCol'));
          // $.alert(this.$i18n('collaboration.grid.alert.transmitCol'));
          return;
        } else if (rows.length > 1 && window.isSecretLevelEnable) {
          Fiber.message.warning(this.$i18n('collabration.secret.transfer.num.limit'));
          // $.alert(this.$i18n('collabration.secret.transfer.num.limit'));
          return;
        } else if (rows.length > 20) {
          //只能选择20项协同进行转发
          Fiber.message.warning(this.$i18n('collaboration.grid.alert.transmitColOnly20'));
          // $.alert(this.$i18n('collaboration.grid.alert.transmitColOnly20'));
          return;
        }

        console.log('$.ctp.trigger', 'beforeTransmitCol', rows);
        const sendDevelop = $.ctp.trigger('beforeTransmitCol', rows);
        if (!sendDevelop) {
          return;
        }

        for (let i = 0; i < rows.length; i++) {
          const selectedObj = rows[i];
          const app = selectedObj.applicationCategoryKey || selectedObj.app;
          if (app == 19 || app == 20 || app == 21) {
            //公文不允许转发协同
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.DocumentNotForwardCol'));
            // $.alert(this.$i18n('collaboration.grid.alert.DocumentNotForwardCol'));
            return;
          } else if (app == '32') {
            //信息报送不允许转发协同
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.InfoNotForwardCol'));
            // $.alert(this.$i18n('collaboration.grid.alert.InfoNotForwardCol'));
            return;
          } else if (app == 81) {
            //模板审批不允许转发协同
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.InfoNotTemplateApproveColl'));
            // $.alert(this.$i18n('collaboration.grid.alert.InfoNotTemplateApproveColl'));
            return;
          } else if (app == 4) {
            Fiber.message.warning(this.$i18n('govdoc.grid.alert.DocumentNotForwardCol'));
            // $.alert(this.$i18n('govdoc.grid.alert.DocumentNotForwardCol'));
            return;
          }
        }

        const data = [];
        for (let i = 0; i < rows.length; i++) {
          let summaryId, affairId, isSuperNode;
          if (rows[i].summaryId && rows[i].affairId) {
            summaryId = rows[i].summaryId;
            affairId = rows[i].affairId;
            isSuperNode = rows[i].superNode;
          } else {
            //首页待办更多是Affair对象
            summaryId = rows[i].objectId;
            affairId = rows[i].id;
          }
          if (listFrom && listFrom == 'listWaitSend') {
            if (rows[i].templeteId) {
              //var r = cm.checkTemplateCanUse(selectBox[i].templeteId);
              let r = callBackendMethod('colManager', 'isTemplateDeleted', rows[i].templeteId);
              if (r == '1') {
                //被删除
                Fiber.message.warning(this.$i18n('template.coll.not.ues.js', rows[i].subject));
                // $.alert(this.$i18n('template.coll.not.ues.js', rows[i].subject));
                return;
              }
            }
          }

          if (isSuperNode === true) {
            Fiber.message.warning(this.$i18n('workflow.supernode.msg.not_transmit.js'));
            // $.alert(this.$i18n('workflow.supernode.msg.not_transmit.js'));
            return;
          }

          data[i] = { summaryId: summaryId, affairId: affairId };
        }

        this.transmitColById(data);
      },
      transmitColById(data) {
        let checkPermissionData = '';
        let doForwardData = '';

        data.forEach((item) => {
          doForwardData += item.summaryId + '_' + item.affairId + ',';
          checkPermissionData += item.affairId + ',';
        });

        const result = window.callBackendMethod(
          'colManager',
          'checkForwardPermission',
          checkPermissionData
        );

        if (result && result instanceof Array && result.length > 0) {
          //以下协同不能转发，请重新选择
          toastForward.call(this, result);
          return;
        }

        let _self = this;

        const dialog = $.dialog({
          id: 'showForwardDialog',
          height: '400',
          width: '550',
          url:
            window._ctxPath +
            '/collaboration/collaboration.do?method=showForward&data=' +
            doForwardData,
          title: this.$i18n('common.toolbar.transmit.col.label'),
          targetWindow: window.getCtpTop(),
          isClear: false,
          transParams: {
            commentContent: ''
          },
          buttons: [
            {
              id: 'okButton',
              text: this.$i18n('common.button.ok.label'),
              btnType: 1,
              handler: function handler() {
                dialog.getReturnValue();
              },
              OKFN: function () {
                dialog.close();
                _self.initTableData();
              }
            },
            {
              id: 'cancelButton',
              text: this.$i18n('common.button.cancel.label'),
              handler: function handler() {
                dialog.close();
              }
            }
          ]
        });
      }, //ajax判断事项是否可用。
      transmitMail() {
        const emailShow = window._hasPlugin('webmail');
        if (emailShow) {
          //需要判断是否只勾选了一项，并给出相应的提示
          // var selectBox =grid.grid.getSelectRows();
          const selectedLength = this.selectedRows.length;
          if (selectedLength === 0) {
            //请选择要转发的协同!
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.transmitCol'));
            // $.alert(this.$i18n('collaboration.grid.alert.transmitCol'));
            return;
          } else if (selectedLength > 1) {
            //只能选择一项协同进行转发
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.transmitColOnlyOne'));
            // $.alert(this.$i18n('collaboration.grid.alert.transmitColOnlyOne'));
            return;
          }
          // for(var i=0; i<selectedLength; i++){
          const selectedObj = this.selectedRows[0];
          const app = selectedObj.applicationCategoryKey || selectedObj.app;
          if (app == '19' || app == '20' || app == '21' || app == '4') {
            //公文不允许转发协同
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.DocumentNotForwardEmail'));
            // $.alert(this.$i18n('collaboration.grid.alert.DocumentNotForwardEmail'));
            return;
          } else if (app == '32') {
            //信息报送不允许转发邮件
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.InfoNotForwardEmail'));
            // $.alert(this.$i18n('collaboration.grid.alert.InfoNotForwardEmail'));
            return;
          } else if (app == '81') {
            //协同模板不允许转发邮件
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.InfoNotTemplateApproveEmail'));
            // $.alert(this.$i18n('collaboration.grid.alert.InfoNotTemplateApproveEmail'));
            return;
          }
          // }

          let summaryId, affairId, isSuperNode;
          summaryId = selectedObj.summaryId || selectedObj.objectId;
          affairId = selectedObj.affairId || selectedObj.id;
          isSuperNode = selectedObj.superNode;

          const ocipParams = [{ summaryId, affairId, isSuperNode }];
          console.log('$.ctp.trigger', 'beforeTransmitMail', ocipParams);
          const sendDevelop = $.ctp.trigger('beforeTransmitMail', ocipParams);
          if (!sendDevelop) {
            return;
          }

          const canTrans = window.callBackendMethod(
            'secretAjaxManager',
            'canTransSecretLevel',
            summaryId
          );
          if (canTrans == false) {
            Fiber.message.warning(this.$i18n('collaboration.grid.alert.noTransSecretData'));
            // $.alert(this.$i18n('collaboration.grid.alert.noTransSecretData'));
            return;
          }

          const result = window.callBackendMethod('colManager', 'checkForwardPermission', affairId);
          if (result && result instanceof Array && result.length > 0) {
            //以下协同不能转发，请重新选择
            toastForward.call(this, result);
            return;
          }

          if (isSuperNode === true) {
            Fiber.message.warning(this.$i18n('workflow.supernode.msg.not_transmit.js'));
            // $.alert(this.$i18n('workflow.supernode.msg.not_transmit.js'));
            return;
          }
          //跳转门户菜单，需要确认资源
          const params = {};
          params.title = this.$i18n('common.toolbar.transmit.mail.label');
          if (window.getCtpTop() && window.getCtpTop().showMenu) {
            window
              .getCtpTop()
              .showMenu(
                window._ctxPath +
                  '/collaboration/collaboration.do?method=forwordMail&summaryId=' +
                  summaryId +
                  '&affairId=' +
                  affairId,
                null,
                null,
                null,
                params
              );
          } else {
            window.showMenu(
              window._ctxPath +
                '/collaboration/collaboration.do?method=forwordMail&summaryId=' +
                summaryId +
                '&affairId=' +
                affairId,
              null,
              null,
              null,
              params
            );
          }
        }
      },
      // 删除事件
      deleteCol() {
        collaboration.deleteItems(this.selectedRows, this.deleteCallback);
      },
      deleteCallback(data) {
        if (data && data.success) {
          this.initTableData();
        }
      },
      batchHandler(chooseData, callback) {
        console.log('$.ctp.trigger', 'beforeBatchDealColl');
        const sendDevelop = $.ctp.trigger('beforeBatchDealColl', chooseData);
        if (!sendDevelop) {
          return;
        }
        const process = new window.BatchProcess();
        chooseData.forEach((item) => {
          if (item) {
            let affairId = item.affairId;
            let category = item.category || '1';
            let subject = item.subject;
            let summaryId = item.summaryId;

            if (category == 81) {
              Fiber.message.warning(this.$i18n('collaboration.template.approve.bath.noinfo'));
              // $.alert(this.$i18n('collaboration.template.approve.bath.noinfo'));
              return;
            }

            if (process.batchOpinion == '0' || process.batchOpinion == null) {
              process.batchOpinion =
                item.disAgreeOpinionPolicy == null
                  ? '0'
                  : item.disAgreeOpinionPolicy == '1'
                  ? '3'
                  : '0'; //意见是否必填，3,不同意时，意见必填
            }

            process.addData(affairId, summaryId, category, subject);
          }
        });

        if (!process.isEmpty()) {
          process.callBack = callback;
          process.doBatch();
        } else {
          Fiber.message.warning(this.$i18n('collaboration.listPending.selectBatchData'));
          // $.alert(this.$i18n('collaboration.listPending.selectBatchData'));
          return;
        }
      },
      batchAutoRunCallback(data) {
        this.initTableData();
      },
      aiSortClick() {
        // // 智能排序清空右侧查询条件
        // searchobj.g.clearCondition();
        // // 隐藏高级查询
        // if ($('.more_query_area').css('display') !== 'none' && $('#aiSortBtn').is(':checked')) {
        //   openQueryViews('listPending');
        // }
        this.initTableData();
        //更新智能排序开关状态
        var params = new Object();
        params['aiSortValue'] = this.aiSortValueTemp === true ? 'true' : 'false';
        params['openFrom'] = 'listPending';
        params['source'] = 'listPending';
        callBackendMethod('pendingManager', 'updateAISortValue', params, {
          success: function (data) {}
        });
      },

      getSearchValueObj() {
        const result = {};
        // 智能查询参数
        let toTab = this.statisticTabsValue;
        if (toTab == 'overdue') {
          result.coverTime = '1';
        } else if (toTab == 'sevenDayOverdue') {
          result.sevenDayOverdue = 'sevenDayOverdue';
        } else if (toTab == 'mydept') {
          result.myDept = 'myDept';
        } else if (toTab == 'fromleader') {
          result.myLeader = 'myLeader';
        }
        result.aiSort = this.aiSortValueTemp === true ? 'true' : 'false';
        result.templeteIds = this.urlParamObj.textfield || '';

        if (this.searchValue) {
          // 标题
          result.subject = this.searchValue;
        }

        for (let key in this.searchConditionsObj) {
          const value = this.searchConditionsObj[key];
          if (value.startDate || value.endDate) {
            result[key] = value.startDate + '#' + value.endDate;
          } else if (value instanceof Array) {
            result[key] = value.join(',');
          } else {
            result[key] = value;
          }
        }

        return result;
      },

      handleTableChange(page, pageSize) {
        this.pagination.page = page;
        this.pagination.pageSize = pageSize;
        this.initTableData();
      },
      paginationShowSizeChange(current, size) {
        this.pagination.page = 1;
        this.pagination.pageSize = size;
        this.initTableData();
      },
      onTableRowClick(record, index) {
        this.openDetail(record);
      },
      openDetail(record) {
        //取消加粗
        record.readState = 1;
        if (record.subState == 11) {
          record.subState = 12;
        }

        if (!collaboration.isAffairValid(record.affairId)) {
          return;
        }
        let url =
          _ctxPath +
          '/collaboration/collaboration.do?method=summary&openFrom=listPending&affairId=' +
          record.affairId +
          (window.CsrfGuard ? CsrfGuard.getUrlSurffix() : '');
        let title = record.subject;
        collaboration.doubleClick(url, escapeStringToHTML(title));
      },
      showDetailLogDialog(record) {
        collaboration.showDetailLogDialog(
          record.summaryId,
          record.processId,
          2,
          false,
          record.affairId
        );
      },
      // 智码扫码成功后，智码预处理时，获取解码参数
      getSmartCodeDecodeParam(data) {
        const obj = this.getSearchValueObj();
        obj.openFrom = 'listPending';
        return obj;
      },
      // 智码扫码成功后回调
      smartCodeCallBack(data) {
        collaboration.smartCodeCallBack(data);
      },
      storageChangeEvent(event) {
        /**
         * pendingDoneEvent 处理待办为已办，需要刷新待办列表和已办列表
         * sendEvent 发送协同 需要刷新已发列表和待发列表
         */
        if (event.key == 'pendingDoneEvent') {
          // this.pagination.page = 1;
          this.initTableData();
        }
      },
      formatAffairNodeName(record) {
        return record.affairNodeName == null
          ? record.nodeName
          : record.affairNodeName + '(' + record.nodeName + ')';
      }
    }
  };
</script>

<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss">
  .todo-list-main {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    display: flex;
    flex-direction: column;
    // background-color: #ffffff;
    background-color: #ffffff;

    .search-condition-container {
      margin-left: 20px;
    }

    .todo-list-header {
      display: flex;
      padding: 12px 16px 12px 16px;
      height: 54px;
      box-sizing: border-box;
    }

    .search-part {
      // flex: 1;
      display: flex;
      justify-content: flex-end;
      overflow: hidden;
      margin-left: 100px;
    }

    .todo-list-content {
      position: relative;
      overflow: hidden;
      flex: 1;
      padding: 0 0 0 16px;
      background-color: #ffffff;
      > div {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
      }
    }

    .icon-default {
      font-weight: initial;
    }
  }
</style>
